import asyncio
import time


# 添加关键字 async 使得函数具备协程属性
# print("---------------- 添加关键字 async 使得函数具备协程属性 ----------------")
# async def func():
#     print('111')
#
# if __name__ == '__main__':
#     # 此时函数是异步协程函数，执行得到一个协程对象
#     g = func()
#     # print(g)
#     # 真正的调用协程函数 asyncio.run()
#     asyncio.run(g)



# time.sleep() 属于同步操作
# 异步任务遇到同步操作时失效
# 耗时 t1 + t2 + t3
# print("---------------- time.sleep() 属于同步操作，异步任务遇到同步操作时失效 ----------------")
# async def func1():
#     print('111')
#     time.sleep(3)
#     print('222')
#
# async def func2():
#     print('333')
#     time.sleep(2)
#     print('444')
#
# async def func3():
#     print('555')
#     time.sleep(4)
#     print('666')
#
# if __name__ == '__main__':
#     f1 = func1()
#     f2 = func2()
#     f3 = func3()
#     tasks = [f1, f2, f3]
#
#     t1 = time.time()
#     asyncio.run(asyncio.wait(tasks))
#     t2 = time.time()
#     print(t2 - t1)




# await asyncio.sleep(3)
# 耗时 max(t1, t2, t3)
print("---------------- await asyncio.sleep(3) ----------------")
async def func1():
    print('111')
    await asyncio.sleep(3)
    print('222')

async def func2():
    print('333')
    await asyncio.sleep(2)
    print('444')

async def func3():
    print('555')
    await asyncio.sleep(4)
    print('666')

# 这样写 main 函数太长
# if __name__ == '__main__':
#     f1 = func1()
#     f2 = func2()
#     f3 = func3()
#     tasks = [f1, f2, f3]
#
#     t1 = time.time()
#     asyncio.run(asyncio.wait(tasks))
#     t2 = time.time()
#     print(t2 - t1)



# 官方推荐写法
async def main():
    # 写法 1----------------------------------------------
    # f1 = func1()
    # # 一般 await 挂起操作放在协程对象前
    # await f1

    # 写法 2----------------------------------------------
    tasks = [
        func1(),
        func2(),
        func3()
    ]
    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())
